import axios from "axios";

const controller = new AbortController();

const apiService = axios.create({
  baseURL: process.env.REACT_APP_API_URL || "https://pokeapi.co/api/v2", // Use environment variable or default value
  timeout: 5000, // Set a timeout for all requests
  headers: { "Content-Type": "application/json" },
  signal: controller.signal,
});

// Add a request interceptor
apiService.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    console.log("Do something before request is sent");
    return config;
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error);
  }
);

// 存储 refreshToken 请求的变量
let isRefreshing = false;
// 存储因等待 token 刷新而挂起的请求的数组
let refreshSubscribers = [];

// 订阅 token 刷新操作
function subscribeTokenRefresh(cb) {
  refreshSubscribers.push(cb);
}

// 通知所有订阅者 token 刷新已完成
function onRefreshed(newToken) {
  refreshSubscribers.forEach((cb) => cb(newToken));
  refreshSubscribers = [];
}

// Add a response interceptor
apiService.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    console.log("Do something with response data");
    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    console.log("interceptors.response", error);
    console.log("aaa", apiService);

    const {
      config,
      response: { status, data },
    } = error;

    if (status === 404) {
      console.log(data, `${config.method}: ${config.baseURL}${config.url}`);
    }

    if (status === 401 && data.message === "Token expired") {
      if (!isRefreshing) {
        isRefreshing = true;
        refreshToken().then((accessToken) => {
          isRefreshing = false;
          onRefreshed(accessToken);
        });
      }

      return new Promise((resolve) => {
        subscribeTokenRefresh((accessToken) => {
          // 更新请求头
          config.headers["Authorization"] = "Bearer " + accessToken;
          // 用新令牌重试原请求
          resolve(apiService(config));
        });
      });
    }
    return Promise.reject(error);
  }
);

async function login() {
  const { token, refreshToken } = await apiService.post("/login");
  localStorage.setItem("token", token);
  localStorage.setItem("refreshToken", refreshToken);
}

function refreshToken() {
  // 使用已存储的 refreshToken 发起刷新令牌的请求
  const refreshToken = localStorage.getItem("refreshToken");
  return apiService.post("/refresh-token", { refreshToken });
}

export function abortRequest() {
  controller.abort();
}

export default apiService;
